<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------
namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo  活动报名模型
 * @since 2015-7-13
 */
class ActivityJoinModel extends BaseModel {

    /* 自动验证规则 */
    protected $_validate = array(
    	/* array('user_name', 'require', '用户姓名必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('user_name', '1,10', '用户姓名长度需要在1到10之间', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('mobile_phone', 'require', '手机号必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('mobile_phone', '11', '手机号不符合规格', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('mobile_phone', '/^1[3-8][0-9]{9}$/', '手机号不符合规格', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH), */
    	array('activity_id', 'integer', '活动必须选择', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('join_time', NOW_TIME, self::MODEL_INSERT),
    );

    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function getPk(){
    	return 'activity_join_id';
    }

    /**
     * @todo 用户是否报名过此次活动
     * @param int activity_id 活动id
     * @param int customer_id 用户id
     * @author PHP@妖孽 <dino_ma@163.com>
     */
    public function checkCustomerIsJoinActivity($activity_id,$customer_id){
    	return $this->field('activity_join_id,activity_id,join_time,sign_channel,customer_id,generalize_member_id,ticket_level')->where(array('activity_id'=>$activity_id,'customer_id'=>$customer_id))->find();
    }


    /**
     * 活动报名
     * @return boolean fasle 失败 ， int  成功 返回完整的数据
     * @param type int 0,1 0默认已报名返回用户Id, 1,已报名返回提示信息
     * @author PHP@妖孽 <dino_ma@163.com>
     */
    public function update($data,$type){
    	if(empty($data)){
    		/* 获取数据对象 */
    		$data = $this->create($_POST);
    	}

    	$data['join_time'] = NOW_TIME;
		
//     	$data = $this->create($data);
    	if(empty($data)){
    		$this->error ='数据不能为空.~';
    		return false;
    	}
    	if(preg_match("/^1[3-8][0-9]{9}$/", $data['mobile_phone'])){
    		//手机号
    		$consumer_obj = D('Admin/Customer');
    		if(!$customer_id = $consumer_obj->register($data['mobile_phone'],null,$data['mobile_phone'],$data['customer_name'],7)){
    			$this->error = $consumer_obj->getError();
    			return false;
    		}
    	}else{
    		$customer_id = (int)$data['mobile_phone'];
    	}
    	if($customer_id ==0){
    		$this->error = 'customer_id异常';
    		return false;
    	}
    	$data['customer_id']=$customer_id;
    	//验证是否报过名.然后写主表
//     	$map['activity_id'] = $data['activity_id'];
//     	$map['customer_id'] = $customer_id;
    	$join_info = $this->checkCustomerIsJoinActivity($data['activity_id'],$customer_id);
    	if(!empty($join_info)){
    		$this->error = '此用户已经报过名';
    		$type = (int)$type;
    		if($type ==1){
    			return false;
    		}else{
    			return	$customer_id;
    		}
    		
    	}
    	/* 添加或新增活动配置 */
    	if(empty($data[$this->getPk()])){ //新增数据
    		$data['generalize_member_id']=getGeneralizeMemberId();
    		if($data['generalize_member_id'] !=0){
    			$data['sign_channel'] = 4;//推广报名
    		}
    		$id = $this->add($data); //添加活动配置
    		if(!$id){
    			$this->error = '报名出错！';
    			return false;
    		}
//     		$config_info = D('Admin/ActivityConfig')->getActivityConfig($data['activity_id']);
//     		$this->startTrans();
//     		if(!empty($config_info)){
// 	    		$child_data = $_POST;
// 	    		unset($child_data['consumer_name']);
// 	    		$child_data['activity_join_id']=$id;
// 	    		//写从表
// 	    		if(!M('activity_attached_'.$data['activity_id'])->add($child_data)){
// 	    			$this->rollback();
// 	    			$this->error = '报名附属表写入出错！';
// 	    			return false;
// 	    		}
//     		}
//     		$this->commit();
    		//临时修改
//     		if($data['activity_id'] == 13){
//     			$sms_content = '尊敬的用户：您已成功报名哈尔滨第十四届家博会。10月23日-25日，会展中心，家装建材工长一站服务，期待您的到来。';
//     		}else{
//     			$sms_content = '欢迎您报名哈尔滨家家户户网'.getActivityName($data['activity_id']).'活动';
//     		}
            switch ($data['sign_channel']){
                //0:主动报名;1:票点报名;2:代报名;3:活动现场报名;4:推广报名
                case 0:
                case 1:
                case 2:
                case 4:
                    if ($data['activity_id']!=36){
                        D('Api/Sms','Service')->sendSms($data['mobile_phone'],getActivitySms($data['activity_id']));
                    }
                    //荣欣装饰报名信息
                    if($data['activity_id']==28){
                        D('Api/Sms','Service')->sendSms('13766503661','用户姓名：'.$data['customer_name'].'用户手机号：'.$data['mobile_phone']);
                    }
                    //198
                    if($data['activity_id']==19){
                        D('Api/Sms','Service')->sendSms('18644052197','用户姓名：'.$data['customer_name'].'用户手机号：'.$data['mobile_phone']);
                    }
                    break;
            }
//     		D('Api/Sms','Service')->sendSms($data['mobile_phone'],'欢迎您报名哈尔滨家家户户网'.getActivityName($data['activity_id']).'活动');
//     		return $id;//先返回偏移量,忘记之前用customer_id干了什么,这里主要是给客服系统返回报名接口
    		return $customer_id;
    	} else { //更新数据
    		$this->error = '不允许进行更新';
    	    return false;
//     		$status = $this->save(); //更新活动配置
//     		if(false === $status){
//     			$this->error = '更新出错！';
//     			return false;
//     		}
    	}
    	return $data;
    }

 	/**
 	 * @todo 返回活动报名列表
 	 * @authro PHP@妖孽 <dino_ma@163.com>
 	 */
    public function getJoinList($activity_id,$limit=5,$order='`activity_join_id` desc'){
    	$pre = C('DB_PREFIX');
    	return $this->where(array('activity_id'=>$activity_id))->field('mobile_phone,customer_name')->
    	join("left join {$pre}customer on {$pre}activity_join.customer_id = {$pre}customer.customer_id")->
    	join("join {$pre}customer_detail on {$pre}customer.customer_id = {$pre}customer_detail.customer_id")->
    	order($order)->limit($limit)->select();
    }


    /**
     * @todo 获取活动报名总人数
     * @authro PHP@妖孽 <dino_ma@163.com>
     */
    public function getActivityConsumer($activity_id){
    	$activity_id = (int)$activity_id;
    	if($activity_id ==0 ){
    		return 0;
    	}
    	return $this->where(array('activity_id'=>$activity_id))->count();
    }

    /**
     * @todo 拉取活动中的外部报名数据(sign_channel 0,3,4的数据)
     * @param activity_id 活动id
     * @param offset_id 偏移量
     * @authro PHP@妖孽 <dino_ma@163.com>
     */
    public function getActivityJoinPerson($activity_id,$offset_id){
    	$map = array();
    	$activity_id = (int)$activity_id;
    	if($activity_id ==0){
    		$this->error = '活动参数有问题.~';
    		return false;
    	}
    	$map['activity_id'] = $activity_id;
    	$offset_id = (int)$offset_id;
    	if($offset_id  !=0){
    		$map['activity_join_id'] =array('gt',$offset_id);
    	}
    	$map['sign_channel']=array('in','0,3,4');

    	$count = $this->where($map)->count();
    	if($count > 0 ){
    		$list = $this->field('activity_join_id,activity_id,join_time,sign_channel,customer_id,generalize_member_id,ticket_level')->where($map)->order('activity_join_id asc')->limit(2000)->select();
    		$data['status']  =1;
    		$data['data']['count'] = $count;
    		$data['data']['list'] = $list;
    		return $data;
    	}else {
    		return false;
    	}
    }

    /**
     * @todo 通过活动id,用户id来查询此用户是否报过当前活动,如果报过, 并且是外部数据(0,3,4) 则返回报名信息
     * @param int activity_id 活动id
	 * @param int customer_id 用户id
     * @authro PHP@妖孽 <dino_ma@163.com>
     */
    public function checkCustomerIsJoinActivityByService($activity_id,$customer_id){
    	$call_back = array();
    	$customer_id = (int)$customer_id;
    	if($customer_id == 0 ){
    		$call_back['status'] = 0;
    		$call_back['info'] = '用户参数有问题';
    		return $call_back;
    	}
    	$join_info = $this->checkCustomerIsJoinActivity($activity_id,$customer_id);
    	if(empty($join_info)){
    		$call_back['status'] = 2;
    		$call_back['info'] = '该用户未报名';
    	
    	}else{
    		if(in_array($join_info['sign_channel'], array(0,3,4)) ){
    			$call_back['status'] = 1;
    			$call_back['data']= $join_info;
    		}else{
    			$call_back['status'] = -1;
    			$call_back['info']= '该用户是内部数据不该请求我这的接口';
    		}
    	}
    	return $call_back;
    }

    /**
     * @todo 客服系统通过手机号/用户id来报名某一个活动
     * @param array();
     *
     * <li>activity_id(int)</li>; 活动id 必须存在
     * <li>customer_id(int)</li>; 用户id 必须存在
     * <li>join_time (int10)</li>; 报名时间,如果不存在则设置 NOW_TIME
     * <li>sign_channel (int)</li>; 报名渠道只接收1和,2
     * <li>generalize_member_id (int)</li>; 推广人id 必须存在
     * <li>ticket_level (int)</li>; 票别 0,1
     * @param int or string(11) customer_id用户id
     * @authro PHP@妖孽 <dino_ma@163.com>
     */
    public function serviceCustomerJoinActivity($data){
    	if(!array_key_exists('activity_id', $data)){
    		$this->error = '缺少活动id';
    		return false;
    	}
    	if(!array_key_exists('customer_id', $data)){
    		$this->error = '缺少用户id';
    		return false;
    	}
    	if(!array_key_exists('join_time', $data)){
    		$join_time  = NOW_TIME;
    	}else{
    		$join_time = (int)$data['join_time'];
    	}
    	if(!array_key_exists('sign_channel', $data)){
    		$this->error = '缺少报名渠道';
    		return false;
    	}
    	if(!array_key_exists('generalize_member_id', $data)){
    		$generalize_member_id = 0;
    	}else{
    		$generalize_member_id = (int)$data['generalize_member_id'];
    	}

    	if(!array_key_exists('ticket_level', $data)){
    		$this->error = '缺少报名票别';
    	}
    	$activity_id = (int)$data['activity_id'];
    	if($activity_id ==0){
    		$this->error = '活动Id有问题';
    		return false;
    	}
    	$sign_channel = (int)$data['sign_channel'];
    	if(!in_array($sign_channel, array(1,2))){
    		$this->error = '报名渠道有问题';
    		return false;
    	}

    	$ticket_level = (int)$data['ticket_level'];
    	if(!in_array($ticket_level, array(0,1))){
    		$this->error = '报名票别有问题';
    		return false;
    	}
    	$customer_id = $data['customer_id'];
    	$map = array();//
    	$customer_service_obj = D('Admin/Customer','Service');
    	//如果是手机号的话那么判断用户是否存在,存在则返回customer_id,如果不存在则注册用户返回customer_id
    	if(preg_match('/^1[3-8][0-9]{9}$/', $customer_id) ){
    		//调用用户系统中的方法
    		$mobile_phone = $customer_id;
    		$customer_id = $customer_service_obj->register($customer_id,null,$customer_id,$customer_name='',7);
    		
    	}else{
    		if($customer_id ==0){
    			$this->error = '用户Id有问题';
    			return false;
    		}
    		$is_true = $customer_service_obj->checkCustomerIdIsTrue($customer_id);
    		//去看用户id是否存在.否则抛异常
    		if(false == $customer_id){
    			$this->error = '该用户不存在';
    			return false;
    		}
    		$mobile_phone = getCustomerName($customer_id);

    	}
    	$join_info = $this->checkCustomerIsJoinActivity($activity_id, $customer_id);
    	if(!empty($join_info)){
    		$this->error = '该用户已经报过名';
    		return false;
    	}
    	$data['customer_id']=$customer_id;
    	//进行报名操作
    	if($activity_join_id = $this->add($data)){
    		$data['activity_join_id']=$activity_join_id;
    		//临时修改
//     		if($activity_id == 13){
//     			$sms_content = '尊敬的用户：您已成功报名哈尔滨第十四届家博会。10月23日-25日，会展中心，家装建材工长一站服务，期待您的到来。';
//     		}else{
//     			$sms_content = '欢迎您报名哈尔滨家家户户网'.getActivityName($data['activity_id']).'活动';
//     		}
    		D('Api/Sms','Service')->sendSms($mobile_phone,getActivitySms($activity_id));
    		return $data;
    	}else{
    		$this->error = '报名失败';
    		return false;
    	}

    }


    /**
     * @todo 客服系统转化的报名更改状态
     * @param int activity_join_id 活动表报名主键
     *  @return bool true/false
     */
    public function isServiceChange($activity_join_id){
    	$activity_join_id = (int)$activity_join_id;
    	$call_back = array();
    	if($activity_join_id ==0){
    		$call_back['status'] = 0;
    		$call_back['info'] = '参数有问题';
    		return $call_back;
    	}
    	$join_info = $this->where(array('activity_join_id'=>$activity_join_id))->find();
    	if(empty($join_info)){
    		$call_back['status'] = -1;
    		$call_back['info'] = '该数据异常~请联系宋爱萍和马胜杰(1)';
    	}else{
    		if(in_array($join_info['sign_channel'], array(0,3,4))){
    			//修改状态
    			$status = $this->where(array('activity_join_id'=>$activity_join_id))->save(array('is_call_back'=>1));
    			if(false === $status){
    				$call_back['status'] = 0;
    				$call_back['info'] = '该数据转操作失败~';
    			}else{
    				$call_back['status'] = 1;
    			}
    		}else{
    			//打回
    			$call_back['status'] = -1;
    			$call_back['info'] = '该数据为内部报名数据不能被转化~';
    		}
    	}
    	return $call_back;
    }
}

